//
//  AlarmListViewController.m
//  RONGAO
//
//  Created by wei wang on 2017/7/4.
//  Copyright © 2017年 wei wang. All rights reserved.
//
#import <IOTCamera/AVIOCTRLDEFs.h>

#import "AlarmListViewController.h"
#import "AddAlarmDeviceViewController.h"
#import "Alarm433Device.h"

#import "AVIOCTRLDEFuserdefineds.h"
#import "wifi_433_info.h"
#import "PresetInfo.h"

#define ALERT_TAG_DELETE    100

@interface AlarmListViewController ()<UITableViewDataSource,UITableViewDelegate,MyCameraDelegate>
@property (strong, nonatomic) IBOutlet UITableView *tableView;

/** delIndexPath **/
@property(nonatomic,assign) NSIndexPath * delIndexPath;

/** isRecvDel **/
@property(nonatomic,assign) BOOL isRecvDel;

/** isRecvPresetList **/
@property(nonatomic,assign) BOOL isRecvPresetList;

/** selectIndex **/
@property(nonatomic,assign) NSInteger selectIndex;


@end

@implementation AlarmListViewController


- (void)viewWillAppear:(BOOL)animated {
    
    self.camera.delegate2 = self;
    [super viewWillAppear:animated];

}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNavigationStyle];
    [self presetSMsgAVIoctrlGetList];

}

- (void)viewDidUnload {
    
    self.camera = nil;
    [super viewDidUnload];
    
}


- (void)presetSMsgAVIoctrlGetList
{
    SmsgAVIoctrlGetAllPresetNameReq *s = (SmsgAVIoctrlGetAllPresetNameReq *)malloc(sizeof(SmsgAVIoctrlGetAllPresetNameReq));
    memset(s, 0, sizeof(SmsgAVIoctrlGetAllPresetNameReq));
    
    s->command_type = PRESET_TYPE_GET;
    
    [self.camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_GETTING_PRESET_NAMELIST_REQ
                           Data:(char *)s
                       DataSize:sizeof(SmsgAVIoctrlGetAllPresetNameReq)];
    
    free(s);
    NSLog(@"presetSMsgAVIoctrlGetList");
    
}

- (void)onRightButtonClick:(id)sender{
    
    NSInteger type = self.typeInt;
    NSLog(@"type:%ld",(long)type);
    NSInteger num = 0;
    for (int i = 0; i < [self.deviceListArr count]; i++) {
        
        Alarm433Device *dev = (Alarm433Device *)[self.deviceListArr objectAtIndex:i];
        
        if (type == dev.device_type) {
            num++;
        }
        
    }
    
    NSString *defAlias = [NSString stringWithFormat:@"%@%ld", [self rowToTitle:self.typeInt], num+1];
    NSLog(@"defAlias:%@", defAlias);
    
    AddAlarmDeviceViewController *vc = [[AddAlarmDeviceViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.camera = self.camera;
    vc.typeInt = type;
    vc.defaultAlias = [[NSString alloc] initWithString:defAlias];
    vc.titleName = [self rowToTitle:self.typeInt];
    [self.navigationController pushViewController:vc animated:YES];

    
}


- (NSString *)rowToTitle:(NSInteger)row {
    NSString *str = [NSString stringWithFormat:@""];
    
    switch (row) {
        case 0:
            str = @"遥控器";
            break;
        case 1:
            str = @"门磁";
            break;
        case 2:
            str = @"红外";
            break;
        case 3:
            str = @"烟感";
            break;
        case 4:
            str = @"气感";
            break;
        case 5:
            str = @"警笛";
            break;
        default:
            str = @"其他";
            break;
    }
    
    return str;
}



#pragma mark - --------------------------UITableView dataSource--------------------------

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.deviceListArr.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 56;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSUInteger row = [indexPath row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    }
    Alarm433Device *dev = (Alarm433Device *)[self.deviceListArr objectAtIndex:row];
    
    NSLog(@"-----------cellForRowAtIndexPath   dev.key:%@, dev.alias:%@, dev.device_alarmed:%ld, dev.alarm_ptz_preset:%ld, dev.device_closed:%ld", dev.key, dev.alias, (long)dev.device_alarmed, (long)dev.alarm_ptz_preset, (long)dev.device_closed);
    
    
    NSString *aliasStr = [NSString stringWithFormat:@"%@", dev.alias];
    
    cell.textLabel.text = aliasStr;

    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
    
}
#pragma mark - --------------------------UITableView delegate--------------------------


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}


#pragma mark 在滑动手势删除某一行的时候，显示出更多的按钮
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    // 添加一个删除按钮
    Alarm433Device *dev = [self.deviceListArr objectAtIndex:indexPath.row];

    UITableViewRowAction *delet = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {

        SmsgAVIoctrlDeleteDevicesReq *s = malloc(sizeof(SmsgAVIoctrlDeleteDevicesReq));
        memset(s, 0, sizeof(SmsgAVIoctrlDeleteDevicesReq));
        
        s->num_ = 1;
        memcpy(s->device_id, [dev.key UTF8String], sizeof(s->device_id));
        NSLog(@"s->device_id:%s", s->device_id);
        
        [self.camera sendIOCtrlToChannel:0
                               Type:IOTYPE_USER_IPCAM_433_DELETED_DEVICE_REQ
                               Data:(char *)s
                           DataSize:sizeof(SmsgAVIoctrlDeleteDevicesReq)];
        free(s);

        [SVProgressHUD showInfoWithStatus:@"删除中请等待"];
        
    }];
    
    UITableViewRowAction *moreRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"重命名" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"重命名" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        
        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
            textField.placeholder = @"请输入名称";
        }];
        __weak typeof(alertController) alere = alertController;
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        __weak typeof(self) weakself = self;
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            if (![NSString isContainsTwoEmoji:alere.textFields.firstObject.text]&&[alere.textFields.firstObject.text length]<=8){
                
                dev.alias = alere.textFields.firstObject.text;
                SmsgAVIoctrlSet433DevicesAliasReq *s = malloc(sizeof(SmsgAVIoctrlSet433DevicesAliasReq));
                memset(s, 0, sizeof(SmsgAVIoctrlSet433DevicesAliasReq));
                
                memcpy(s->device_id, [dev.key UTF8String], 16);
                memcpy(s->device_alias , [dev.alias UTF8String], 16);
                
                s->is_alarmed = dev.device_alarmed;
                s->ptz_preset = dev.alarm_ptz_preset;
                s->device_closed = dev.device_closed;
                
                [self.camera sendIOCtrlToChannel:0
                                       Type:IOTYPE_USER_IPCAM_433_SET_ALIAS_REQ
                                       Data:(char *)s
                                   DataSize:sizeof(SmsgAVIoctrlSet433DevicesAliasReq)];
                free(s);

                
                [weakself.tableView reloadData];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:@"输入名称过长或输入了非法字符"];
                
            }
            
        }];
        
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
        [SVProgressHUD showInfoWithStatus:@"修改中请等待"];

    }];
    
    moreRowAction.backgroundColor = [UIColor colorWithHexString:@"dab866"];
    
    return @[delet,moreRowAction];
}




#pragma mark - MyCameraDelegate Methods
- (void)camera:(MyCamera *)camera_ _didReceiveIOCtrlWithType:(NSInteger)type Data:(const char *)data DataSize:(NSInteger)size {
    NSLog(@"ALVC _didReceiveIOCtrlWithType type:%lx", (long)type);
    
    if (camera_ == self.camera && type == IOTYPE_USER_IPCAM_433_DELETED_DEVICE_RESP) {
        
        SmsgAVIoctrlDeleteDevicesResp *s = (SmsgAVIoctrlDeleteDevicesResp*)data;
        
        
        NSLog(@"IOTYPE_USER_IPCAM_433_DELETED_DEVICE_RESP  s->result_:%d",  s->result_);
        if (0 == s->result_) {
            
            if (self.delIndexPath) {
                NSInteger row = [self.delIndexPath row];
                NSLog(@"_didReceiveIOCtrlWithType self.delIndexPath row:%ld", (long)row);
                
                Alarm433Device *dev = [[Alarm433Device alloc] init];
                dev = (Alarm433Device *)[self.deviceListArr objectAtIndex:row];
                
                [self.deviceListArr removeObjectAtIndex:row];
                
                [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:self.delIndexPath] withRowAnimation:UITableViewRowAnimationFade];
                
                self.delIndexPath = nil;
            }
            
            
            [self.tableView reloadData];
        } else {
            
        }
    }
    
    if (type == IOTYPE_USER_IPCAM_GETTING_PRESET_NAMELIST_RESP) {
        SmsgAVIoctrlGetAllPresetNameResp *s = (SmsgAVIoctrlGetAllPresetNameResp*)data;
        NSLog(@"IOTYPE_USER_IPCAM_GETTING_PRESET_NAMELIST_RESP s->command_types_:%d, s->result_:%d",
              s->command_type, s->result);
        
        self.isRecvPresetList = YES;
        
        if (0 == s->result) {
            
            if (s->command_type == PRESET_TYPE_GET) {
                
                
            } else if (s->command_type == PRESET_TYPE_SET) {
                
            }
            
            
            for (int i=0; i<16; i++) {
                PresetInfo *pInfo = [[PresetInfo alloc] initWithPresetInfoType:0];
                pInfo.presetID = (s->name_list[i].index) + 1; // index(0~15)
                pInfo.presetIsValid = s->name_list[i].is_valid;
                //pInfo.presetAlias = [NSString stringWithUTF8String:s->name_list[i].preset_name];
                pInfo.presetAlias = [[NSString alloc] initWithCString:s->name_list[i].preset_name encoding:NSUTF8StringEncoding];
                
                
                NSLog(@"i:%d   pInfo.presetID:%ld, pInfo.presetIsValid:%lu, pInfo.presetAlias:%@  [pInfo.presetAlias length]:%lu  preset_name[0]:|%c|", i, (long)pInfo.presetID, (unsigned long)pInfo.presetIsValid, pInfo.presetAlias, (unsigned long)[pInfo.presetAlias length], s->name_list[i].preset_name[0]);
                
            }
            
            [self.tableView reloadData];
        }
    }
    
    if (type == IOTYPE_USER_IPCAM_433_SET_ALIAS_RESP) {
        SmsgAVIoctrlSet433DevicesAliasResp *s = (SmsgAVIoctrlSet433DevicesAliasResp*)data;
        NSLog(@"IOTYPE_USER_IPCAM_433_SET_ALIAS_RESP s->result_:%d", s->result_);
        if (0 == s->result_) {
            
        }
    }
    
}



- (NSMutableArray *)deviceListArr{
    
    if (!_deviceListArr) {
        
        _deviceListArr = [NSMutableArray array];
        
    }
    return _deviceListArr;
}

- (void)setNavigationStyle{
    
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self setNavigationTitle:@"报警器接入" titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
    [self setRightButtonImage:[UIImage imageNamed:@"icon_add_nor"]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
